package com.lbjhan.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lbjhan.rpc.common.RpcRequest;
import com.lbjhan.rpc.common.RpcResponse;
import com.lbjhan.rpc.consumer.client.RpcNettyClient;
import com.lbjhan.rpc.consumer.client.RpcNettyResponseClient;
import com.lbjhan.rpc.consumer.client.RpcZKClient;
import com.lbjhan.rpc.pojo.User;
import com.lbjhan.rpc.serializer.JacksonSerializer;
import org.springframework.stereotype.Component;

import java.lang.reflect.*;
import java.util.Map;
import java.util.UUID;

/**
 * 客户端代理类
 * 1. 封装request请求对象
 * 2. 创建RpcNettyClient对象
 * 3. 发送消息
 */
@Component
public class RpcClientResponseProxy {

    public Object createProxy(Class<?> clazz){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 1. 封装request请求对象
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setClassName(method.getDeclaringClass().getName());
                System.out.println("class = " + method.getDeclaringClass().getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                //2. 创建RpcNettyClient对象
//                RpcNettyResponseClient rpcNettyResponseClient = new RpcNettyResponseClient();
                String ipPort = RpcZKClient.getInstance().getIpPort(rpcRequest.getClassName());
                RpcNettyResponseClient rpcNettyResponseClient = RpcNettyResponseClient.getInstance(ipPort);
                //3. 发送消息并得到响应结果
                RpcResponse rpcResponse = (RpcResponse)rpcNettyResponseClient.send(rpcRequest);
                if(null != rpcResponse.getError()){
                    throw new RuntimeException(rpcResponse.getError());
                }
                //4. 返回结果
                Object result = rpcResponse.getResult();
                return JSON.parseObject(JSONArray.toJSONString(result), method.getReturnType());
            }
        });
    }
}
